/*
 * Galaxium Messenger
 * Copyright (C) 2008 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Timers;

using Anculus.Core;

using Galaxium.Core;

namespace Galaxium.Gui
{
	public enum TweenMethod { Linear }
	
	public class Tween
	{
		public event EventHandler ValueChanged;
		
		double _value = 0;
		double _target = 0;
		double _initial = 0;
		double _points = 15;
		TweenMethod _method = TweenMethod.Linear;
		Timer _timer = new Timer ();
		
		public TweenMethod Method
		{
			get { return _method; }
			set { _method = value; }
		}
		
		public double Points
		{
			get { return _points; }
			set { _points = value; }
		}
		
		public double Value
		{
			get { return _value; }
			set { _value = value; }
		}
		
		public Tween (double initial)
		{
			_value = initial;
			
			_timer.Elapsed += TimerElapsed;
		}
		
		public Tween ()
			: this (0)
		{
		}
		
		public void Begin (double target, double time)
		{
			_initial = _value;
			_target = target;
			
			_timer.Interval = time / _points;
			_timer.Enabled = true;
		}
		
		double GetStep ()
		{
			if (_method == TweenMethod.Linear)
				return (_target - _initial) / _points;
			
			return 0;
		}
		
		void TimerElapsed (object sender, ElapsedEventArgs args)
		{
			_value += GetStep ();
			
			if (((_target > _initial) && (_value >= _target)) ||
			    ((_target < _initial) && (_value <= _target)))
			{
				_value = _target;
				_timer.Enabled = false;
			}
			
			ThreadUtility.SyncDispatch (new VoidDelegate (delegate
			{
				OnValueChanged ();
			}));
		}
		
		protected virtual void OnValueChanged ()
		{
			if (ValueChanged != null)
				ValueChanged (this, EventArgs.Empty);
		}
	}
}
